package com.example.app;


import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 客户端心跳检测类
 */
public class Heartbeats implements Runnable{

    // 创建HttpClient
    HttpClient client = HttpClient.newHttpClient();
    private static final Logger log = LogManager.getLogger(Heartbeats.class);

    @Override
    public void run() {

        //读取INSTALLDIR\config.ini文件中的account值
        String account = ConfigReader.readConfig("account");
        String phone = ConfigReader.readConfig("phone");
        String legal = ConfigReader.readConfig("legal");

        if (account == null || account.isEmpty()) {
            log.error("account 未设置：config.ini 中缺少 [app]/account");
            return;
        }
        log.info("current account: " + account);

        String jsonData = """
                    {
                        "account": "%s",
                        "phone": "%s",
                        "legal": "%s"
                    }
                    """.formatted(account, phone, legal);


        while (true){
            try {
                
                // 构建 HttpRequest（GET，携带账号作为查询参数）
                String url = "http://192.168.0.175:28084/heartbeat" ;
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(url))
                        .header("Content-Type", "application/json; charset=utf-8")
                        .header("Accept", "application/json")
                        .POST(HttpRequest.BodyPublishers.ofString(jsonData))
                        .build();

                // 发送同步请求，并指定响应体以字符串形式处理
                HttpResponse<String> response = client.send(request , HttpResponse.BodyHandlers.ofString());

                // 输出响应状态码和响应体
                log.info("Status Code: {}", response.statusCode());
                log.info("Response Body: {}", response.body());

                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // 恢复中断并退出循环
                Thread.currentThread().interrupt();
                log.warn("心跳线程被中断，停止发送心跳", e);
                break;
            } catch (IOException e) {
                log.error("心跳请求失败", e);
                throw new RuntimeException(e);
            }
        }
    }
}
